package logic

import (
	"2210a/user-profile/pkg"
	"context"
	"net/http"
	"path/filepath"
	"time"

	"2210a/user-profile/userprofileapi/internal/svc"
	"2210a/user-profile/userprofileapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadImageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadImageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadImageLogic {
	return &UploadImageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadImageLogic) UploadImage(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, header, err := req.FormFile("image")
	if err != nil {
		return &types.Response{
			Code:    500,
			Message: "图片获取信息错误",
			Data:    nil,
		}, nil
	}
	ext := filepath.Ext(header.Filename)
	if ext != ".jpeg" && ext != ".png" {
		return &types.Response{
			Code:    500,
			Message: "图片进行上传.jpeg和.png格式的",
			Data:    nil,
		}, nil
	}
	if header.Size > 8*1024*1024 {
		return &types.Response{
			Code:    500,
			Message: "图片大小不超过8M",
			Data:    nil,
		}, nil
	}
	FileName := time.Now().Format("20060102150405") + ext
	upload, err := pkg.QiNiuYunUpload(file, FileName)
	if err != nil {
		return &types.Response{
			Code:    500,
			Message: "图片上传失败",
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Code:    500,
		Message: "图片上传成功",
		Data:    upload,
	}, nil
}
